package com.ww.dynamic.spel;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.util.Date;

public class PropertyExprSample {

    public static void main(String[] args) {
        // 构建一个对象
        User user = new User();
        user.setUserName("tom");
        user.setLastVisit(new Date());
        user.setCredits(100);
        user.setPlaceOfBirth(new PlaceOfBirth("中国", "厦门"));

        // 构建SpEL解析上下文
        SpelExpressionParser parser = new SpelExpressionParser();
        StandardEvaluationContext context = new StandardEvaluationContext(user);

        // 基本属性值获取
        String userName = (String) parser.parseExpression("userName").getValue(context);
        int credits = (Integer) parser.parseExpression("credits + 10").getValue(context);

        System.out.println(userName);
        System.out.println(credits);
    }

    @ToString
    @Data
    static class User {

        private String userName;

        private Date lastVisit;

        private Integer credits;

        private PlaceOfBirth placeOfBirth;

		public String getUserName() {
			return userName;
		}

		public void setUserName(String userName) {
			this.userName = userName;
		}

		public Date getLastVisit() {
			return lastVisit;
		}

		public void setLastVisit(Date lastVisit) {
			this.lastVisit = lastVisit;
		}

		public Integer getCredits() {
			return credits;
		}

		public void setCredits(Integer credits) {
			this.credits = credits;
		}

		public PlaceOfBirth getPlaceOfBirth() {
			return placeOfBirth;
		}

		public void setPlaceOfBirth(PlaceOfBirth placeOfBirth) {
			this.placeOfBirth = placeOfBirth;
		}
    }

    @ToString
    @Data
    static class PlaceOfBirth {

        private String province;

        private String city;

		public PlaceOfBirth() {
			super();
			// TODO Auto-generated constructor stub
		}

		public PlaceOfBirth(String province, String city) {
			super();
			this.province = province;
			this.city = city;
		}

		public String getProvince() {
			return province;
		}

		public void setProvince(String province) {
			this.province = province;
		}

		public String getCity() {
			return city;
		}

		public void setCity(String city) {
			this.city = city;
		}
    }
}
